import type { StudentUnitList, StudentUnitParams } from '@/api/types/student'
import { handleApiError } from '@/api'
import { studentApi } from '@/api/modules/student'
import { CourseType } from '@/enums/course'
import { defineStore } from 'pinia'

interface State {
  unitListData: StudentUnitList
}

export const useStudentUnitStore = defineStore(
  'studentUnit',
  {
    state: (): State => {
      return {
        unitListData: {
          studentId: 0,
          course: {
            id: 0,
            name: '',
            type: undefined,
          },
          units: [],
        },
      }
    },
    getters: {
      // 是否为体验课
      isExperienceCourse: state => state.unitListData.course.type === CourseType.EXPERIENCE ? 1 : 0,
    },
    actions: {
      updateCourseType(type: CourseType) {
        this.unitListData.course.type = type
      },
      async fetchUnitList(params: StudentUnitParams) {
        const [error, data] = await studentApi.getStudentUnitList(params)
        if (error) {
          return handleApiError(error)
        }
        this.unitListData = data.data
      },
    },
    persist: true,
  },
)
